package com.xc.word.wordUtil;

import com.alibaba.fastjson.JSONObject;
import com.xc.common.tool.Helper;
import com.xc.ksxt.entity.ChapterEntity;
import com.xc.ksxt.entity.ImportRecordEntity;
import com.xc.ksxt.entity.LibChoiceEntity;
import com.xc.ksxt.entity.LibQuestionEntity;
import com.xc.ksxt.service.ImportRecordService;
import com.xc.ksxt.service.LibChoiceService;
import com.xc.ksxt.service.LibQuestionService;
import com.xc.sys.entity.SysUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTObject;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.w3c.dom.Node;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class WordReader {
    @Autowired
    private LibQuestionService libQuestionService;
    @Autowired
    private LibChoiceService libChoiceService;
    public JSONObject readWordImgToHtml(XWPFDocument document, ImportRecordEntity ire, Long majorId, HashMap<String, ChapterEntity> chapterMap, SysUserEntity me) throws Exception {
        JSONObject res = new JSONObject();
        res.put("code", 1);
        res.put("msg", "导入异常");
        List<XWPFParagraph> ps = document.getParagraphs();
        HashMap<String,Integer> questionTypeMap = new HashMap<>();
        questionTypeMap.put("[单选题]",1);
        questionTypeMap.put("[多选题]",2);
        questionTypeMap.put("[判断题]",3);
        questionTypeMap.put("[简答题]",4);
        questionTypeMap.put("[论述题]",5);
        int questionType = -1;
        StringBuffer buf = new StringBuffer();
        LibQuestionEntity libq = null;
        LibChoiceEntity libc = null;
        List<LibChoiceEntity> libcs = null;
        int orderno = 1;
        int n = 0;
        for (XWPFParagraph p : ps) {
            String text = p.getText();
            if(text.startsWith("[单选题]")||text.startsWith("[多选题]")||text.startsWith("[判断题]")||
                    text.startsWith("[简答题]")||text.startsWith("[论述题]")){
                n++;
                libq = newQuestionEntity(ire);
                libq.setOrderno(orderno++);
                buf = new StringBuffer();
                String pefixText = StringUtils.substring(text,0,5);
                String questionText = StringUtils.substring(text,5);
                questionType = questionTypeMap.get(pefixText);
                buf.append(questionText);
                libq.setQuestionType(questionType);
                continue;

            }else if(text.startsWith("A.")||text.startsWith("B.")||text.startsWith("C.")||text.startsWith("D.")||text.startsWith("E.")||text.startsWith("F.")
                    ||text.startsWith("G.")||text.startsWith("H.")||text.startsWith("A．")||text.startsWith("B．")||text.startsWith("C．")
                    ||text.startsWith("D．")||text.startsWith("E．")||text.startsWith("F．")
                    ||text.startsWith("G．")||text.startsWith("H．")){
                if(text.startsWith("A.")||text.startsWith("A．")){
                    libq.setText(buf.toString());
                    libcs = new ArrayList<>();
                }else {
                    //持久化上一个选项
                    libc.setText(buf.toString());
                    libChoiceService.save(libc);
                }
                //新的选项
                libc = newChoiceEntity(ire);
                libc.setIndexLetter(text.substring(0,1));
                libc.setLibQuestionId(libq.getId());
                libcs.add(libc);
                buf = new StringBuffer();
                String choiceText = text.trim();
                buf.append(choiceText.substring(2).trim());
                continue;

            }else if(text.startsWith("答案：")||text.startsWith("答案:")){
                if(questionType==4){//简答题
                    libq.setText(buf.toString());
                }else if(questionType==5){
                    libc.setText(buf.toString());
                    libChoiceService.save(libc);
                }else{
                    libc.setText(buf.toString());
                }
                buf = new StringBuffer();
                String answerTxt = text.substring(3).trim();
                if(answerTxt.length()>=1){
                    if(questionType<4){//选择题、判断题
//								libc.setText(buf.toString());//设置刚结束的选项
                        libChoiceService.save(libc);
                        char[] letterArr = answerTxt.toCharArray();
                        for (char c : letterArr) {
                            for (LibChoiceEntity libChoiceEntity : libcs) {
                                if(libChoiceEntity.getIndexLetter().equals(c+"")){
                                    libChoiceEntity.setRight(1);
                                    libChoiceService.save(libChoiceEntity);
                                }
                            }
                        }
                    }else{
                        buf.append(answerTxt);
                    }

                }
                continue;
            }else if(text.startsWith("解析：")||text.startsWith("解析:")){
                if(buf.length()>0){
                    if(questionType==4){
                        libq.setAnswerText(buf.toString());
                    }else if(questionType==5){
                        libc.setAnswerText(buf.toString());
                        libChoiceService.save(libc);
                    }

                }
                buf = new StringBuffer();
            }else if(text.startsWith("章节：")||text.startsWith("章节:")){
                String zjText = StringUtils.deleteWhitespace(text.substring(3).trim());
                ChapterEntity chapterEntity = chapterMap.get(zjText);
                if(chapterEntity==null){
                    res.put("code",1);
                    res.put("msg","第"+(n)+"题，章节不正确（"+zjText+"）");
                    return res;
                }
                if(libq!=null&&!libq.getText().isEmpty()){
                    String jxText = buf.toString().substring(3).trim();//设置解析
                    libq.setAnalysis(jxText);
                    libq.setPianId(chapterEntity.getPianId());
                    libq.setChapterId(chapterEntity.getId());
                    libq.setCategoryId(chapterEntity.getCategoryId());
                    libq.setCreateTime(LocalDateTime.now());
                    libq.setCreateUserId(me.getId());
                    libq.setMajorId(majorId + "");
                    libQuestionService.save(libq);
                    libc = null;
                }
                buf = new StringBuffer();
                continue;
            }else {//论述题的小题

            }

        }
        System.out.println(buf);
        return res;
    }
    private String jiexiRun(XWPFParagraph paragraph) throws Exception {
        List<XWPFRun> runs = paragraph.getRuns();
        StringBuilder buf = new StringBuilder();
        for (XWPFRun run : runs) {
            List<XWPFPicture> pics = run.getEmbeddedPictures();
            for (XWPFPicture pic : pics) {
                XWPFPictureData pdata = pic.getPictureData();
                double width = pic.getWidth();
                byte[] data = pdata.getData();
                String imgUrl = getImageUrl(data, "n.png");
                buf.append("<p><img alt='' src='" + imgUrl + "'></p>");
            }
        }
        return buf.toString();
    }
    private LibQuestionEntity newQuestionEntity(ImportRecordEntity ire){
        LibQuestionEntity libq = new LibQuestionEntity();//新建题干对象
        libq.setRecordId(ire.getId());
        //libq.setLibId(ire.getLibId());
        libq.setId(Helper.getSnowId()+"");
        libq.setDelFlag(1);
        libq.setCreateTime(LocalDateTime.now());
        return libq;
    }
    private LibChoiceEntity newChoiceEntity(ImportRecordEntity ire){
        LibChoiceEntity libc = new LibChoiceEntity();//新建题干对象
        libc.setRecordId(ire.getId());
        libc.setLibId(ire.getLibId());
        libc.setCreateTime(LocalDateTime.now());
        libc.setDelFlag(1);
        libc.setRight(2);
        return libc;
    }
    private String getImageUrl(byte[] data,String fileName) throws Exception{
        String imgUrl="";
        Long res =new Date().getTime();
        //设置文件存储路径，可以存放在你想要指定的路径里面
        String rootPath="D:/mimi/"+ File.separator+"upload/images/";
        // 新文件名
        String newFileName =res + fileName.substring(fileName.lastIndexOf("."));
        //新文件
        File newFile=new File(rootPath+"/"+newFileName);
        //判断文件目录是否存在
        if(!newFile.getParentFile().exists()){
            //如果目标文件所在的目录不存在，则创建父目录
            newFile.getParentFile().mkdirs();
        }

        //-------把图片文件写入磁盘 start ----------------
        FileOutputStream fos = new FileOutputStream(newFile);
        fos.write(data);
        fos.close();
        //-------把图片文件写入磁盘 end ----------------
        //服务器图片地址
        String baseURL = "http://127.0.0.1:8080/mimi/upload/images/";
        imgUrl=baseURL+newFileName;

        return imgUrl;
    }
}
